#include "function_base_test.h"
#include "viml/compiler.h"
#include "viml/vm.h"
#include <gtest/gtest.h>

namespace viml {

/**
 * 函数调用错误处理测试
 */
class FunctionErrorTest : public FunctionCallTestBase {
protected:
    void SetUp() override {
        FunctionCallTestBase::SetUp();
    }
};

// FC-201: 测试参数数量不匹配
TEST_F(FunctionErrorTest, WrongArgumentCount) {
    std::string source = R"(
function test_func(a, b)
    return a + b
endfunction

" 调用时参数数量不匹配
let result = test_func(1)  " 应该抛出错误
)";
    
    // 期望编译或执行时抛出异常
    EXPECT_THROW(
        compileAndExecute(source, "WrongArgumentCount"),
        VMException
    );
}

// FC-202: 测试调用未定义函数
TEST_F(FunctionErrorTest, UndefinedFunction) {
    std::string source = R"(
" 调用未定义的函数
let result = undefined_func(1, 2)
)";
    
    // 期望执行时抛出异常
    EXPECT_THROW(
        compileAndExecute(source, "UndefinedFunction"),
        VMException
    );
}

// FC-203: 测试栈溢出（深度递归）
TEST_F(FunctionErrorTest, StackOverflow) {
    std::string source = R"(
function deep_recursion(n)
    if n <= 0
        return 0
    endif
    return deep_recursion(n - 1)
endfunction

" 调用深度递归，可能导致栈溢出
let result = deep_recursion(10001)
)";
    
    // 期望执行时抛出异常
    EXPECT_THROW(
        compileAndExecute(source, "StackOverflow"),
        std::exception
    );
}

// FC-204: 测试无限递归
TEST_F(FunctionErrorTest, InfiniteRecursion) {
    std::string source = R"(
function infinite_recursion()
    return infinite_recursion()
endfunction

infinite_recursion()
)";
    
    // 期望执行时抛出异常
    EXPECT_THROW(
        compileAndExecute(source, "InfiniteRecursion"),
        VMException
    );
}

// FC-205: 测试调用非函数值
TEST_F(FunctionErrorTest, NonFunctionCall) {
    std::string source = R"(
let not_a_function = 42

" 尝试调用非函数值
let result = not_a_function(1, 2)
)";
    
    // 期望执行时抛出异常
    EXPECT_THROW(
        compileAndExecute(source, "NonFunctionCall"),
        VMException
    );
}

// FC-206: 测试函数内未定义变量访问
TEST_F(FunctionErrorTest, UndefinedVariableInFunction) {
    std::string source = R"(
function test_undefined()
    echo undefined_variable  " 访问未定义变量
endfunction

test_undefined()
)";
    
    // 期望执行时抛出异常
    EXPECT_THROW(
        compileAndExecute(source, "UndefinedVariableInFunction"),
        std::exception
    );
}

// FC-207: 测试函数参数类型错误
TEST_F(FunctionErrorTest, ParameterTypeError) {
    std::string source = R"(
function expect_number(x)
    return x + 1
endfunction

" 传递不兼容的参数类型
let result = expect_number("not_a_number")
)";
    
    compileAndExecute(source, "ParameterTypeError");
    // 注意：某些类型错误可能不会抛出异常，而是进行类型转换
}

// FC-208: 测试空函数体执行
TEST_F(FunctionErrorTest, EmptyFunctionBody) {
    std::string source = R"(
function empty_func()
    " 空函数体
endfunction

empty_func()
)";
    
    // 空函数体应该正常执行
    compileAndExecute(source, "EmptyFunctionBody");
}

} // namespace viml